<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemTenantApi } from '#/api/system/tenant';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { COMMON_OPT } from '@vben/constants';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteTenant,
  deleteTenantList,
  exportTenant,
  getTenantPage,
} from '#/api/system/tenant';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 导出表格 */
async function handleExport() {
  const data = await exportTenant(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '租户.xls', source: data });
}

/** 创建租户 */
function handleCreate() {
  formDrawerApi.setData(null).open();
}
/** 复制租户 */
function handleCopy(row: SystemTenantApi.Tenant) {
  row.OPT_TYPE = COMMON_OPT.COPY;
  formDrawerApi.setData(row).open();
}
/** 编辑租户 */
function handleEdit(row: SystemTenantApi.Tenant) {
  row.OPT_TYPE = COMMON_OPT.UPDATE;
  formDrawerApi.setData(row).open();
}

/** 删除租户 */
async function handleDelete(row: SystemTenantApi.Tenant) {
  ElMessageBox.confirm(`确定删除租户【${row.name}】吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting', [row.name]),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deleteTenant(row.id!)
        .then(() => {
          ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
          handleRefresh();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
}

/** 批量删除租户 */
async function handleDeleteBatch() {
  ElMessageBox.confirm(`确定删除选中的租户吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting'),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deleteTenantList(checkedIds.value)
        .then(() => {
          ElMessage.success($t('ui.actionMessage.deleteSuccess'));
          handleRefresh();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemTenantApi.Tenant[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    // 搜索栏展开折叠按钮是折叠 true 折叠 false 收起
    collapsed: true,
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getTenantPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      search: true,
      custom: true,
      export: false,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemTenantApi.Tenant>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<SystemTenantApi.Tenant>) {
  switch (code) {
    case 'copy': {
      handleCopy(row);
      break;
    }

    case 'delete': {
      handleDelete(row);
      break;
    }
    case 'edit': {
      handleEdit(row);
      break;
    }
  }
}
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="handleRefresh" />
    <Grid table-title="租户列表">
      <template #toolbar-tools>
        <ElButton type="primary" @click="handleCreate"> 新增 </ElButton>
        <ElButton type="primary" @click="handleExport"> 导出 </ElButton>
        <ElButton
          type="danger"
          @click="handleDeleteBatch"
          :disabled="isEmpty(checkedIds)"
        >
          批量删除
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
